home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / PRODUCTCONTEXT.PY < prev    next >
Encoding:
Python Source  |  2000-11-20  |  13.7 KB  |  357 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """Objects providing context for product initialization
  65. """
  66. from AccessControl.PermissionRole import PermissionRole
  67. import Globals, os, OFS.ObjectManager, OFS.misc_, Products
  68. import AccessControl.Permission
  69. from HelpSys import HelpTopic, APIHelpTopic
  70. from HelpSys.HelpSys import ProductHelp
  71. from FactoryDispatcher import FactoryDispatcher
  72. from zLOG import LOG, WARNING
  73. import string, os.path
  74. import stat
  75. from DateTime import DateTime
  76.  
  77. import ZClasses # to enable 'PC.registerBaseClass()'
  78.  
  79. if not hasattr(Products, 'meta_types'): Products.meta_types=()
  80. if not hasattr(Products, 'meta_classes'):
  81.     Products.meta_classes={}
  82.     Products.meta_class_info={}
  83.  
  84. class ProductContext:
  85.  
  86.     def __init__(self, product, app, package):
  87.         self.__prod=product
  88.         self.__app=app
  89.         self.__pack=package
  90.  
  91.     def registerClass(self, instance_class=None, meta_type='', 
  92.                       permission=None, constructors=(),
  93.                       icon=None, permissions=None, legacy=(),
  94.         ):
  95.         """Register a constructor
  96.  
  97.         Keyword arguments are used to provide meta data:
  98.  
  99.         instance_class -- The class of the object that will be created.
  100.         
  101.           This is not currently used, but may be used in the future to
  102.           increase object mobility.
  103.  
  104.         meta_type -- The kind of object being created
  105.            This appears in add lists.  If not specified, then the class
  106.            meta_type will be used.
  107.  
  108.         permission -- The permission name for the constructors.
  109.            If not specified, then a permission name based on the
  110.            meta type will be used.
  111.  
  112.         constructors -- A list of constructor methods
  113.           A method can me a callable object with a __name__
  114.           attribute giving the name the method should have in the
  115.           product, or the method may be a tuple consisting of a
  116.           name and a callable object.  The method must be picklable.
  117.  
  118.           The first method will be used as the initial method called
  119.           when creating an object.
  120.  
  121.         icon -- The name of an image file in the package to
  122.                 be used for instances. Note that the class icon
  123.                 attribute will be set automagically if an icon is
  124.                 provided.
  125.  
  126.         permissions -- Additional permissions to be registered
  127.            If not provided, then permissions defined in the
  128.            class will be registered.
  129.         
  130.         legacy -- A list of legacy methods to be added to ObjectManager
  131.                   for backward compatibility
  132.  
  133.         """
  134.         app=self.__app
  135.         pack=self.__pack
  136.         initial=constructors[0]
  137.         tt=type(())
  138.         productObject=self.__prod
  139.         pid=productObject.id
  140.  
  141.         if icon and instance_class is not None:
  142.             setattr(instance_class, 'icon', 'misc_/%s/%s' %
  143.                     (pid, os.path.split(icon)[1]))
  144.  
  145.         OM=OFS.ObjectManager.ObjectManager
  146.  
  147.         if permissions:
  148.             for p in permissions:
  149.                 if type(p) is tt:
  150.                     p, default= p
  151.                     AccessControl.Permission.registerPermissions(
  152.                         ((p, (), default),))
  153.                 else:
  154.                     AccessControl.Permission.registerPermissions(
  155.                         ((p, ()),))
  156.  
  157.         ############################################################
  158.         # Constructor permission setup
  159.         if permission is None:
  160.             permission="Add %ss" % (meta_type or instance_class.meta_type)
  161.  
  162.         if type(permission) is tt:
  163.             permission, default = permission
  164.         else:
  165.             default = ('Manager',)
  166.  
  167.         pr=PermissionRole(permission,default)
  168.         AccessControl.Permission.registerPermissions(
  169.             ((permission, (), default),))
  170.         ############################################################
  171.  
  172.         for method in legacy:
  173.             if type(method) is tt: name, method = method
  174.             else: name=method.__name__
  175.             if not OM.__dict__.has_key(name):
  176.                 setattr(OM, name, method)
  177.                 setattr(OM, name+'__roles__', pr)
  178.  
  179.         if type(initial) is tt: name, initial = initial
  180.         else: name=initial.__name__
  181.  
  182.         fd=getattr(pack, '__FactoryDispatcher__', None)
  183.         if fd is None:
  184.             class __FactoryDispatcher__(FactoryDispatcher):
  185.                 "Factory Dispatcher for a Specific Product"
  186.  
  187.             fd = pack.__FactoryDispatcher__ = __FactoryDispatcher__
  188.  
  189.         if not hasattr(pack, '_m'): pack._m=fd.__dict__
  190.         m=pack._m
  191.  
  192.         Products.meta_types=Products.meta_types+(
  193.             { 'name': meta_type or instance_class.meta_type,
  194.               'action': ('manage_addProduct/%s/%s' % (pid, name)),
  195.               'product': pid,
  196.               'permission': permission,
  197.               },)
  198.  
  199.         m[name]=initial
  200.         m[name+'__roles__']=pr
  201.  
  202.         for method in constructors[1:]:
  203.             if type(method) is tt: name, method = method
  204.             else:
  205.                 name=os.path.split(method.__name__)[-1]
  206.             if not productObject.__dict__.has_key(name):
  207.                 m[name]=method
  208.                 m[name+'__roles__']=pr
  209.  
  210.         if icon:
  211.             name=os.path.split(icon)[1]
  212.             icon=Globals.ImageFile(icon, self.__pack.__dict__)
  213.             icon.__roles__=None
  214.             if not hasattr(OFS.misc_.misc_, pid):
  215.                 setattr(OFS.misc_.misc_, pid, OFS.misc_.Misc_(pid, {}))
  216.             getattr(OFS.misc_.misc_, pid)[name]=icon
  217.  
  218.  
  219.     def registerZClass(self, Z, meta_type=None):
  220.         #
  221.         #   Convenience method, now deprecated -- clients should
  222.         #   call 'ZClasses.createZClassForBase()' themselves at
  223.         #   module import time, passing 'globals()', so that the
  224.         #   ZClass will be available immediately.
  225.         #
  226.         base_class=Z._zclass_
  227.         if meta_type is None:
  228.             if hasattr(base_class, 'meta_type'): meta_type=base_class.meta_type
  229.             else:                                meta_type=base_class.__name__
  230.  
  231.         module=base_class.__module__
  232.         name=base_class.__name__
  233.             
  234.         key="%s/%s" % (module, name)
  235.  
  236.         if module[:9]=='Products.': module=string.split(module,'.')[1]
  237.         else: module=string.split(module,'.')[0]
  238.             
  239.         info="%s: %s" % (module, name)
  240.  
  241.         Products.meta_class_info[key]=info # meta_type
  242.         Products.meta_classes[key]=Z
  243.         
  244.         
  245.  
  246.     def registerBaseClass(self, base_class, meta_type=None):
  247.         #
  248.         #   Convenience method, now deprecated -- clients should
  249.         #   call 'ZClasses.createZClassForBase()' themselves at
  250.         #   module import time, passing 'globals()', so that the
  251.         #   ZClass will be available immediately.
  252.         #
  253.         Z = ZClasses.createZClassForBase( base_class, self.__pack )
  254.         return Z
  255.  
  256.  
  257.     def getProductHelp(self):
  258.         """
  259.         Returns the ProductHelp associated with the current Product.
  260.         """
  261.         return self.__prod.__of__(self.__app.Control_Panel.Products).getProductHelp()
  262.  
  263.     def registerHelpTopic(self, id, topic):
  264.         """
  265.         Register a Help Topic for a product.
  266.         """
  267.         self.getProductHelp()._setObject(id, topic)
  268.  
  269.     def registerHelpTitle(self, title):
  270.         """
  271.         Sets the title of the Product's Product Help
  272.         """
  273.         h = self.getProductHelp()
  274.         if getattr(h, 'title', None) != title:
  275.             h.title = title
  276.  
  277.     def registerHelp(self, directory='help', clear=1):
  278.         """
  279.         Registers Help Topics for all objects in a directory.
  280.  
  281.         Nothing will be done if the files in the directory haven't
  282.         changed since the last registerHelp call.
  283.  
  284.         'clear' indicates whether or not to delete all existing
  285.         Topics from the Product.
  286.  
  287.         HelpTopics are created for these kind of files
  288.  
  289.         .dtml            -- DTMLHelpTopic
  290.         .html .htm       -- TextHelpTopic        
  291.         .stx .txt        -- STXHelpTopic
  292.         .jpg .png .gif   -- ImageHelpTopic
  293.         .py              -- APIHelpTopic
  294.         """
  295.         help=self.getProductHelp()
  296.         path=os.path.join(Globals.package_home(self.__pack.__dict__),
  297.                           directory)
  298.  
  299.         # If help directory does not exist, log a warning and return.
  300.         try:
  301.             dir_mod_time=DateTime(os.stat(path)[stat.ST_MTIME])
  302.         except OSError, (errno, text):
  303.             LOG("Zope", WARNING, '%s: %s' % (text, path))
  304.             return
  305.  
  306.         # test to see if nothing has changed since last registration
  307.         if help.lastRegistered is not None and \
  308.                 help.lastRegistered >= dir_mod_time:
  309.             return
  310.         help.lastRegistered=DateTime()
  311.  
  312.         if clear:
  313.             for id in help.objectIds('Help Topic'):
  314.                 help._delObject(id)
  315.  
  316.         for file in os.listdir(path):
  317.             ext=os.path.splitext(file)[1]
  318.             ext=string.lower(ext)
  319.             if ext in ('.dtml',):
  320.                 ht=HelpTopic.DTMLTopic(file, '', os.path.join(path,file))
  321.                 self.registerHelpTopic(file, ht)
  322.             elif ext in ('.html', '.htm'):
  323.                 ht=HelpTopic.TextTopic(file, '', os.path.join(path,file))
  324.                 self.registerHelpTopic(file, ht)
  325.             elif ext in ('.stx', '.txt'):
  326.                 title=string.split(open(os.path.join(path,file),'rb').readline(), ':')[0]
  327.                 ht=HelpTopic.STXTopic(file, title, os.path.join(path, file))
  328.                 self.registerHelpTopic(file, ht)
  329.             elif ext in ('.jpg', '.gif', '.png'):
  330.                 ht=HelpTopic.ImageTopic(file, '', os.path.join(path, file))
  331.                 self.registerHelpTopic(file, ht)
  332.             elif ext in ('.py',):
  333.                 ht=APIHelpTopic.APIHelpTopic(file, '', os.path.join(path, file))
  334.                 self.registerHelpTopic(file, ht)
  335.             
  336.